package com.efounder.util;

import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;

import com.efounder.widget.ESPWebView;
import com.pansoft.appcontext.AppConstant;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

//10.80.0.104:8080/EnterpriseServer

public class MyStaticMobilePlayWebView {

	/*
	 * public static void setContext(Context mcontext){ context = mcontext; }
	 */
	static ESPWebView wv;
	static ImageView kuaizhao;
	static Context context1;
	static String formtitle;


	static StorageUtil storageUtilforwebview;
	static String ServerURL;
	public static String getFormtitle() {
		return formtitle;
	}

	public static void setFormtitle(String formtitle) {
		MyStaticMobilePlayWebView.formtitle = formtitle;
	}

	private static final String TAG = "Mystaticwebview";

	public static void newInstance(Context context) {
		context1 = context;



		wv = null;
		initWebView(context);
		initWebViewContainer(context);
	}
	public static void setContext(Context context){
		context1 = context;
	}

	static FrameLayout fl;

	//加载本地js。css文件
	public static ESPWebView initWebView(Context context) {
		if (wv == null) {
			System.out.println("init...........");
			wv = new ESPWebView(context);

		/*	wv.setWebChromeClient(new WebChromeClient(
					){

						@Override
						public boolean onJsAlert(WebView view, String url,
								String message, JsResult result) {
							System.out.println("onJsAlert------"+message);
							return super.onJsAlert(view, url, message, result);
						}
				
			});*/
			// //网页基础目录
			String urlhtml = AppConstant.APP_ROOT
					+ "/res/unzip_res/HTML5/GWTMobilePlay.html";
			//String baseUrl = "http://10.80.0.104:8080/EnterpriseServer/GWTFormPlay.html";
			storageUtilforwebview = new StorageUtil(context1, "storage");
			String address = storageUtilforwebview.getString("address","");
			String path = storageUtilforwebview.getString("path","");
			String port = storageUtilforwebview.getString("port", "8080");
			boolean isSafe = storageUtilforwebview.getBoolean("isSafe", true);
			String protocol = null;
			if (isSafe) {
				protocol = "https";
			}else {
				protocol = "http";
			} 
			ServerURL = protocol + "://" + address+"/"+path;
			String baseUrl = ServerURL + "/GWTFormPlay.html";
			StringBuffer txtContent = new StringBuffer();
			// 每次读取的byte数
			byte[] b = new byte[8 * 1024];
			InputStream in = null;
			try {
				// 文件输入流
				in = new FileInputStream(urlhtml);
				while (in.read(b) != -1) {
					// 字符串拼接
					txtContent.append(new String(b));
				}
				// 关闭流
				in.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			final String mimeType = "text/html"; // image/jpeg etc
			final String encoding = "utf-8"; // base64 etc
			String data = txtContent.toString(); // 相对路径，相对基础目录而言

			wv.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, null);


			wv.setWebViewClient(new WebViewClient() {

				@Override
				public void onLoadResource(WebView view, String url) {

					// System.out.println("url===="+url);
					// Log.i(TAG, "onLoadResource url="+url);

					super.onLoadResource(view, url);
				}

				@Override
				public void onPageFinished(WebView view, String url) {
					super.onPageFinished(view, url);
					//Log.i(TAG, "---------------onPageFinished");

				}

				@Override
				/*public WebResourceResponse shouldInterceptRequest(WebView view,
						String url) {
					//当前时间
					Log.i("TimeCheck", "开始加载本地js————————"+new Date(System.currentTimeMillis()));
					WebResourceResponse response = null;
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

						if (url.contains("ui-bg_glass_85_edeff1_1x400.png")
								|| url.contains("favicon.ico")
								|| url.contains("ui-bg_inset-hard_100_fcfdfd_1x100.png")
								|| url.contains("ui-bg_glass_75_fef1bd_1x400.png")) {
							url = AppConstant.APP_ROOT
									+ "/res/unzip_res/Image/menu2n.png";
							 Log.i(TAG, "shouldInterceptRequest url="+url);
							
							try {
								FileInputStream localCopy = new FileInputStream(
										url);
								

								response = new WebResourceResponse("text/png",
										"UTF-8", localCopy);
							} catch (IOException e) {
								e.printStackTrace();
							}

						}else if ((url.contains("GWTMobilePlay/")
								|| url.contains("js/") || url.contains("css/")||url.contains("ImageSpace/"))
								) {
							String content = url.substring(
									url.indexOf(ServerURL)
											+ (ServerURL)
													.length(), url.length());

							url = AppConstant.APP_ROOT + "/res/unzip_res/HTML5"
									+ content;
							 Log.i(TAG, "shouldInterceptRequest url="+url);
							try {
								FileInputStream localCopy = new FileInputStream(
										url);
								  PipedOutputStream out = new PipedOutputStream();
								  PipedInputStream in = new PipedInputStream(out);
								  in.connect(out);
								 
								  
						           
						            try {
			                            out.write(url.getBytes());
			                           
			                            out.close();
			                            
			                            }catch (Exception e){
			                                e.printStackTrace();
			                            }
						           
								response = new WebResourceResponse(null,
										"UTF-8", in);
								
							} catch (IOException e) {
								e.printStackTrace();
							} finally {
							 System.out.println(url+".........over");
							}

						}
					}
					Log.i("TimeCheck","加载js完成————————"+new Date(System.currentTimeMillis()));
					//
					return response;
				}*/
			public WebResourceResponse shouldInterceptRequest(WebView view,
						String url) {
					//当前时间
					System.out.println("开始加载本地js————————"+new Date(System.currentTimeMillis()));
					WebResourceResponse response = null;
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

						if (url.contains("ui-bg_glass_85_edeff1_1x400.png")
								|| url.contains("favicon.ico")
								|| url.contains("ui-bg_inset-hard_100_fcfdfd_1x100.png")
								|| url.contains("ui-bg_glass_75_fef1bd_1x400.png")) {
							url = AppConstant.APP_ROOT
									+ "/res/unzip_res/Image/menu2n.png";
							 Log.i(TAG, "shouldInterceptRequest url="+url);
							
							try {
								FileInputStream localCopy = new FileInputStream(
										url);
								

								response = new WebResourceResponse("text/png",
										"UTF-8", localCopy);
							} catch (IOException e) {
								e.printStackTrace();
							}

						}else if ((url.contains("GWTMobilePlay/")
								|| url.contains("js/") || url.contains("css/")||url.contains("ImageSpace/"))
								) {
							String content = url.substring(
									url.indexOf(ServerURL)
											+ (ServerURL)
													.length(), url.length());

							url = AppConstant.APP_ROOT + "/res/unzip_res/HTML5"
									+ content;
							 Log.i(TAG, "shouldInterceptRequest url="+url);
							try {
								FileInputStream localCopy = new FileInputStream(
										url);

								response = new WebResourceResponse(null,
										"UTF-8", localCopy);
							} catch (IOException e) {
								e.printStackTrace();
							} finally {
							 System.out.println(url+".........over");
							}

						}
					}
					System.out.println("加载js完成————————"+new Date(System.currentTimeMillis()));
					//
					return response;
				}
			});

		}
		return wv;
	}


	public static FrameLayout initWebViewContainer(Context context) {
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		if (fl == null) {
			fl = new FrameLayout(context);
			fl.setLayoutParams(params);
		} else {
		}
		return fl;

	}

    //得到唯一实例
	public static ESPWebView getWv() {
		if(wv==null){
		 initWebView(context1);
		}
		return wv;
	}

	public static ImageView getKuaiZhao() {
		return kuaizhao;
	}

	public static FrameLayout getFl() {

		return fl;
	}
	
	public static void setScaleVsalue(View view, double size) {
		Class classType;
		Method method = null;
		try {
			classType = WebView.class;
			for (Method item : classType.getDeclaredMethods()) {
				if (item.getName().equals("setNewZoomScale")) {
					method = item;
				}
			}
			if (method != null) {
				method.setAccessible(true);
				method.invoke(view, new Object[] { (float) (size / 100.0),
						true, true });
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	} 

}
